/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Principal.java
 *
 * Created on 23-may-2011, 13:17:24
 */

package kinesiologia;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import ClasesKinesiologia.*;
import java.io.File;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import Logic.usuarioLogic;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author Adrian
 */
public class Principal extends javax.swing.JFrame {

    /** Creates new form Principal */
    private List<Paciente> pacientes;
    private List<String> ObraSocial;
    private DefaultTableModel modelo;
    private usuarioLogic user;
    private File formu;
    private coneccion conexion;
    public Principal()
    {
        initComponents();
        user = new usuarioLogic();
        pacientes = new ArrayList<Paciente>();
        ObraSocial = new ArrayList<String>();
        this.btVerP.setEnabled(false);
        conexion = new coneccion();
        this.setTitle("Principal");
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        inimod();
        inicia();
        
    }

    public void inicia()
    {
        File ruta = new File("");


        //Formularios
        formu = new File(ruta.getAbsolutePath()+"\\Formularios");
        if(formu.exists()==false) formu.mkdir();
        //Datos personales
        File DatosP = new File(ruta.getAbsolutePath()+"\\DatosPersonales");
        if(DatosP.exists()==false)
        {
           DatosP.mkdir();
        }
        //pacientes
        List<Paciente> pacientes = (List<Paciente>) user.getallPac();
        for(Paciente p:pacientes)
        {
            this.agregaMod(p);
        }
    }

    

    public void inimod()
    {
        modelo = new DefaultTableModel();
        table.setModel(modelo);
        modelo.addColumn("Nombre y Apellido");
        modelo.addColumn("Documento");
        modelo.addColumn("Edad");
        modelo.addColumn("Localidad");
        modelo.addColumn("Domicilio");
        modelo.addColumn("Telefono");
        modelo.addColumn("Obra Social");
    }
    public void agregaMod(Paciente p)
    {
        
        String[] fila = new String[7];
        fila[0]=p.getApe();
        fila[1]=p.getDoc();
        fila[2]="0";
        //String.valueOf(p.getEdad());
        fila[3]=p.getLoc();
        fila[4]=p.getDom();
        fila[5]=p.getTel();
        fila[6]=p.getOS();
        modelo.addRow(fila);
    }

    private void todosPac()
    {
        this.inimod();
        List<Paciente> pacientes = (List<Paciente>) user.getallPac();
        for(Paciente p:pacientes)
        {
            this.agregaMod(p);
        }
     }
     
    private Paciente buscaPacDoc(String doc)
    {
        Paciente aux=null;
        ResultSet pas = conexion.hacerConsultaSelect("select * from paciente where dni_paciente="+doc);
        if(pas!=null)
        {
            try {
                while (pas.next() == true) {
                    aux = new Paciente(pas.getString("nombre_paciente"), pas.getString("dni_paciente"), pas.getDate("fecha_nacimiento"), pas.getString("nombre_localidad"), pas.getString("domicilio"), pas.getString("telefono"), pas.getString("nombre_obraSocial"));
                }
            } catch (SQLException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return aux;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        btVerP = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jToolBar2 = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem9 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu6 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem7 = new javax.swing.JMenuItem();
        jMenu7 = new javax.swing.JMenu();
        jMenuItem10 = new javax.swing.JMenuItem();
        jMenuItem11 = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Principal");
        setMinimumSize(new java.awt.Dimension(640, 480));

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
            }
        ));
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        jToolBar1.setRollover(true);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/AgregarCuerpo.png"))); // NOI18N
        jButton1.setToolTipText("Agregar Paciente");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        btVerP.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/ver-mas.gif"))); // NOI18N
        btVerP.setToolTipText("Ver Datos del paciente");
        btVerP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btVerPActionPerformed(evt);
            }
        });
        jToolBar1.add(btVerP);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/eliminar.gif"))); // NOI18N
        jButton3.setToolTipText("Eliminar un paciente");
        jButton3.setMaximumSize(new java.awt.Dimension(39, 39));
        jButton3.setMinimumSize(new java.awt.Dimension(39, 39));
        jButton3.setPreferredSize(new java.awt.Dimension(39, 39));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/3ojos_femeninos-eyeblue-thumb.gif"))); // NOI18N
        jButton4.setToolTipText("Ver todos los pacientes");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton4);

        jToolBar2.setRollover(true);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/agregar_favoritos.png"))); // NOI18N
        jButton2.setToolTipText("Agregar Obra Social");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar2.add(jButton2);

        jMenu1.setText("Archivo");

        jMenuItem5.setText("Nuevo Usuario");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem5);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Paciente");
        jMenu3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu3ActionPerformed(evt);
            }
        });

        jMenuItem9.setText("Ver todos los pacientes");
        jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem9ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem9);

        jMenuItem2.setText("Nuevo Paciente");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenu6.setText("Buscar");

        jMenuItem3.setText("Por nombre");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu6.add(jMenuItem3);

        jMenuItem4.setText("Por documento");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu6.add(jMenuItem4);

        jMenu3.add(jMenu6);

        jMenuBar1.add(jMenu3);

        jMenu4.setText("Obra Social");

        jMenuItem7.setText("Agregar/Ver");
        jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem7ActionPerformed(evt);
            }
        });
        jMenu4.add(jMenuItem7);

        jMenuBar1.add(jMenu4);

        jMenu7.setText("Formulario");

        jMenuItem10.setText("Ver formularios");
        jMenuItem10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem10ActionPerformed(evt);
            }
        });
        jMenu7.add(jMenuItem10);

        jMenuItem11.setText("Agregar formulario");
        jMenuItem11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem11ActionPerformed(evt);
            }
        });
        jMenu7.add(jMenuItem11);

        jMenuBar1.add(jMenu7);

        jMenu5.setText("Ayuda");

        jMenuItem6.setText("Acerca de...");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem6);

        jMenuBar1.add(jMenu5);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 699, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        AgregarPaciente Apac = new AgregarPaciente(modelo);
        Apac.show();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
        // TODO add your handling code here:
        this.btVerP.setEnabled(true);
        
    }//GEN-LAST:event_tableMouseClicked

    private void btVerPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btVerPActionPerformed
        // TODO add your handling code here:
        AgregarPaciente pac = new AgregarPaciente(modelo);
        pac.show();
        int fila = table.getSelectedRow();
        Paciente aux = this.buscaPacDoc(String.valueOf(modelo.getValueAt(fila, 1)));
        pac.cambiaDatos(aux,fila);
    }//GEN-LAST:event_btVerPActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        AgregarPaciente  Apac = new AgregarPaciente(modelo);
         Apac.show();
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        AgregarOS aux = new AgregarOS(ObraSocial);
        aux.show();
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        int fila = table.getSelectedRow();
        Paciente aux = this.buscaPacDoc(String.valueOf(modelo.getValueAt(fila, 1)));
        this.pacientes.remove(aux);
        modelo.removeRow(fila);
        ResultSet pas = conexion.hacerConsultaSelect("select * from paciente where dni_paciente='"+aux.getDoc()+"'");
        try {
            pas.first();
            pas.deleteRow();
            conexion.cerrarConeccion();
        } catch (SQLException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        // Buscar por nombre
        String docu = JOptionPane.showInputDialog("Ingrese el apellido y nombre del paciente deceado");
        if(docu != null)
        {
        docu.toLowerCase();
        this.inimod();
        int max,min,total;

        String sub;
        for(Paciente p:pacientes)
        {
            min =0;
            max = docu.length();
            total = p.getApe().length();
            String com = p.getApe().toLowerCase();
            if(com.startsWith(docu) || com.endsWith(docu))
            {
                this.agregaMod(p);
            } else {
                while(max<=total)
                {
                    sub = com.substring(min, max);
                    if(sub.equals(docu)==true)
                    {
                         this.agregaMod(p);
                    }
                    min++;
                    max++;
                }
            }
        }
        }
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        // Busca por DNI
        String docu = JOptionPane.showInputDialog("Ingrese el documento del paciente deceado");
        if(docu != null)
        {
        this.inimod();
        for(Paciente p:pacientes)
        {
            if(docu.equals(p.getDoc()))
            {
                this.agregaMod(p);
            }
        }
        }
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        todosPac();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu3ActionPerformed
        // TODO add your handling code here:
        todosPac();
    }//GEN-LAST:event_jMenu3ActionPerformed

    private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed
        // TODO add your handling code here:
        Runtime r = Runtime.getRuntime();
        try {
            r.exec("explorer.exe "+formu.getCanonicalPath());
        } catch (IOException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenuItem10ActionPerformed

    private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed
        // TODO add your handling code here:
       JFileChooser jfc = new JFileChooser();
       int re = jfc.showOpenDialog(this);
       if(re==JFileChooser.OPEN_DIALOG)
       {
           File aux = jfc.getSelectedFile();
           File rec = new File(formu.getAbsolutePath()+"\\"+aux.getName());
           Ficheros cargar = new Ficheros();
           cargar.copyFile(aux, rec);
       }
    }//GEN-LAST:event_jMenuItem11ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
       System.exit(0);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
        // TODO add your handling code here:
         AgregarOS aux = new AgregarOS(ObraSocial);
         aux.show();
    }//GEN-LAST:event_jMenuItem7ActionPerformed

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
        // TODO add your handling code here:
        Acercade p = new Acercade();
        p.show();
    }//GEN-LAST:event_jMenuItem6ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        // TODO add your handling code here:
        String us,pas1,pas2;
        us=JOptionPane.showInputDialog("Ingrese el nombre de usuario");
        pas1=JOptionPane.showInputDialog("Ingrese Contraseña");
        pas2=JOptionPane.showInputDialog("Ingrese Contraseña nuevamente");

        if(pas1.equals(pas2)==true)
        {
           ResultSet pas = conexion.hacerConsultaSelect("select * from usuario");
        try {
            pas.moveToInsertRow();
            pas.updateString("nombre_Usuario", us);
            pas.updateString("pass", pas1);
            pas.insertRow();
            conexion.cerrarConeccion();
            JOptionPane.showMessageDialog(rootPane, "El usuario ha sido creado satistactoriamente");
        } catch (SQLException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        } else {
            JOptionPane.showMessageDialog(rootPane, "La contraseña introducida no es igual en ambos casos");
        }
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
        // TODO add your handling code here:
          todosPac();
    }//GEN-LAST:event_jMenuItem9ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btVerP;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenu jMenu7;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem10;
    private javax.swing.JMenuItem jMenuItem11;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItem9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables

}
